package com.firesrc.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jodd.db.DbThreadSession;
import jodd.db.oom.sqlgen.DbEntitySql;
import jodd.util.StringUtil;

import com.firesrc.bean.Record;
import com.firesrc.mail.search.SearchMailStrategy;
import com.firesrc.mail.search.SearchMailWhois365Impl;
import com.firesrc.mail.search.SearchMailWhoisSoftImpl;
import com.firesrc.mail.thread.SearchMailExecutor;
import com.firesrc.util.JsoupUtil;

/**
 * Servlet implementation class ChaServlet
 */
public class ChaServlet extends SuperServlet {
	private static final long serialVersionUID = 1L;
	private SearchMailExecutor executor;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		response.setCharacterEncoding("GBK");
		response.setContentType("text/html; charset=gb2312");
		String parameter = request.getParameter("keyword");
		String count = request.getParameter("count");

		executor = new SearchMailExecutor();

		new DbThreadSession(cp);

		String[] split = StringUtil.split(parameter, ",");
		for (String tmpKeyword : split) {
			// executeSingleThread(response, count, strategy, whiso365,
			// tmpKeyword);
			Set<Record> searchMai = executor.searchMail(tmpKeyword, count);

			StringBuffer buffer = new StringBuffer();
			for (Record r : searchMai) {
				if (cache.get(r.getMail()) == null) {
					buffer.append(r.getMail());
					buffer.append(";");

					try {
						DbEntitySql.insert(r).query().executeUpdateAndClose();
					} catch (Exception e) {
						e.printStackTrace();
					}
					cache.put(r.getMail(), r);
				}
			}

			PrintWriter writer = response.getWriter();
			String textArea = "<textarea rows='5' cols='80' >" + buffer.toString() + "</textarea>";

			writer.print("<br/>你查的关键字:<" + tmpKeyword + ">的邮箱是" + searchMai.size() + "条,下面的是具体的邮箱:</br>" + textArea);

		}
	}

	private void executeSingleThread(HttpServletResponse response, String count, String tmpKeyword) throws IOException {
		System.out.println("开始搜索关键字:" + tmpKeyword);
		SearchMailStrategy strategy = new SearchMailWhoisSoftImpl();
		SearchMailStrategy whiso365 = new SearchMailWhois365Impl();
		List<String> list = JsoupUtil.getBaiduUrlListFromKeyword(tmpKeyword, count);
		Set<String> allSet = Collections.synchronizedSet(new HashSet<String>());
		for (String url : list) {
			try {
				Set<String> mailSetFromUrlByWhisoSoft = strategy.getMailListFromUrl(url);
				if (mailSetFromUrlByWhisoSoft.size() == 0) {
					mailSetFromUrlByWhisoSoft = whiso365.getMailListFromUrl(url);
				}

				allSet.addAll(mailSetFromUrlByWhisoSoft);

				Thread.sleep(100);
			} catch (InterruptedException e) {
				Set<String> mailSet365 = whiso365.getMailListFromUrl(url);
				allSet.addAll(mailSet365);
			}

			Record record;
			for (String mail : allSet) {
				if (cache.get(mail) == null) {

					record = new Record();
					record.setId(UUID.randomUUID().toString());
					record.setMail(mail);
					record.setKeyword(tmpKeyword);
					record.setUrl(url);
					try {
						DbEntitySql.insert(record).query().executeUpdateAndClose();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						System.out.println("查询邮箱出错:" + mail + "网址是:" + url);
						System.err.println("错误信息是:--" + e.getMessage());
					}
					// cache.put(mail, mail);
				}
			}
		}

		StringBuffer buffer = new StringBuffer();
		for (String mail : allSet) {
			buffer.append(mail);
			buffer.append(";");
		}

		PrintWriter writer = response.getWriter();
		String textArea = "<textarea rows='5' cols='80' >" + buffer.toString() + "</textarea>";

		writer.print("<br/>你查的关键字:<" + tmpKeyword + ">的邮箱是" + allSet.size() + "条,下面的是具体的邮箱:</br>" + textArea);
	}

}
